package com.arlen.until.http;


import com.alibaba.fastjson.JSON;
import com.arlen.common.constant.GetHttpConstant;
import lombok.NonNull;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import java.util.Map;

//用于发送http请求的工具类
public class Interaction {
    //发送get请求
    public String sendGet(@NonNull String url,Integer type) throws IOException {
        String tokenMess;
        HttpURLConnection httpURLConnection;
        InputStream inputStream = null;
        try {
            URL httpUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            if (httpURLConnection.getResponseCode() != 200) {
                throw new IOException();
            }
            inputStream = httpURLConnection.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder buffer = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                buffer.append(new java.lang.String(bytes, 0, len));
            }
            tokenMess = buffer.toString();
        } finally {
            assert inputStream != null;
            inputStream.close();
        }
        if (type.equals(GetHttpConstant.ANALYSIS.getState())){
            Map map = JSON.parseObject(tokenMess, Map.class);
            return map.get("access_token").toString();
        }

        if (type.equals(GetHttpConstant.NOANALYSIS.getState())){
            return tokenMess;
        }
        return null;
    }

    //发送post请求
    public boolean sendPost(@NonNull String url, String body) throws IOException {
        boolean flag =false;
        URL postUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        //如果想要输出数据就需要设为true 主要是post请求
        connection.setDoOutput(true);
        connection.setDoInput(true); //这样也需要为true 默认就是true
        OutputStream outputStream = connection.getOutputStream();
        //写数据
        outputStream.write(body.getBytes());
        outputStream.close();
        InputStream inputStream = connection.getInputStream();
        //获取响应
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder builder = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1){
            builder.append(new String(bytes,0,len));
        }
        String s = builder.toString();
        System.out.println(s);
        if (!s.contains("errcode")){
            flag = true;
        }

        return flag;
    }

}
